#include "UdpServer.hpp"
#include <memory>
#include <vector>


string Join(const string& str, string ip, uint16_t port)
{
    string prefix = "[" + ip + ":" + to_string(port) + "]# ";
    string ret = prefix + str;
    return ret;
}

bool Check(const string& cmd)
{
    vector<string> key_word = {
        "rm",
        "mv",
        "cp",
        "kill",
        "sudo",
        "unlink",
        "top"
    };
    for(auto& str : key_word)
    {
        if(cmd.find(str) != string::npos)
            return false;
    }
    return true;
}

string ExecuteCommand(const string& cmd, string ip, uint16_t port)
{
    if(!Check(cmd))
        return "false";
    FILE* fp = popen(cmd.c_str(), "r");
    if(fp == nullptr)
        return "";

    string prefix = "[" + ip + ":" + to_string(port) + "]# ";

    char buffer[1024];
    string ret = prefix;
    while(1)
    {
        char* ack = fgets(buffer, sizeof(buffer), fp);
        if(ack == nullptr)
            break;
        
        ret += buffer;        
    }
    pclose(fp);
    return ret;
}


int main(int argc, char* argv[])
{
    if(argc != 2)
    {
        cout << "Usage: " << argv[0] << " port[1024+]" << endl;
        return 1;
    }


    uint16_t port = stoi(argv[1]);
    unique_ptr<UdpServer> ups(new UdpServer(port));
    ups->Init();
    ups->Run(Join);

    return 0;
}